#include <stdio.h>
#include <pthread.h>
#include "sql.h"
#include "mysocket.h"

void* pthread_handle(void* arg);

int main()
{
    pthread_t pid;

    set_signal_handle(SIGCHLD);
    int serverFd = CreateSocket();

    while (1)
    {
        ConnectStruct_t* tmpConnectPtr = (ConnectStruct_t*)malloc(sizeof(ConnectStruct_t));
        tmpConnectPtr->sockLen = sizeof(tmpConnectPtr->sock);//如果不初始化的话会导致接收到的信息是[0.0.0.0:0]
        tmpConnectPtr->fd = accept(serverFd, (Addr*)&tmpConnectPtr->sock, &tmpConnectPtr->sockLen);
        if (tmpConnectPtr->fd < 0)
        {
            free(tmpConnectPtr);
            continue;
        }

            pthread_create(&pid, NULL, pthread_handle, (void*)tmpConnectPtr);
            pthread_detach(pid); 
    }
    pthread_mutex_destroy(&g_db_mutex);
}

void* pthread_handle(void* arg)
{
    ConnectStruct_t* tmpConnect = (ConnectStruct_t*)arg;

    char recv_buffer[BUFSIZ] = { 0 };
    char send_buffer[BUFSIZ] = { 0 };
    char tmpIpBuffer[BUFSIZ] = { 0 };

    size_t recv_bytes;
    size_t send_bytes;//如果一次性传输的数据大于BUFSIZ的话需要先传输多少个字节，这个就会排上用场，现在只是用来看看send函数是否出错。

    while (1)
    {
        /*==========<接收信息>==========*/
        memset(recv_buffer, 0, BUFSIZ);
        recv_bytes = recv(tmpConnect->fd, recv_buffer, sizeof(recv_buffer) - 1, 0);
        if (recv_bytes > 0)
        {
            recv_buffer[recv_bytes] = '\0';
            pthread_mutex_lock(&g_db_mutex);
            printf("[%s:%d]:%s\n", inet_ntop(AF_INET, &tmpConnect->sock.sin_addr, tmpIpBuffer, tmpConnect->sockLen), ntohs(tmpConnect->sock.sin_port), recv_buffer);
            pthread_mutex_unlock(&g_db_mutex);
        }
        else if (recv_bytes == 0)
        {
            pthread_mutex_lock(&g_db_mutex);
            printf("[%s:%d]已断开连接\n", inet_ntop(AF_INET, &tmpConnect->sock.sin_addr, tmpIpBuffer, tmpConnect->sockLen), ntohs(tmpConnect->sock.sin_port));
            pthread_mutex_unlock(&g_db_mutex);
            close(tmpConnect->fd);
            free(tmpConnect);
            break;
        }
        else
        {
            perror("recv");
            close(tmpConnect->fd);
            free(tmpConnect);
            break;
        }

        /*==========<数据处理>==========*/
        pthread_mutex_lock(&g_db_mutex);

        /*接收到的数据操作数据库，数据库输出的数据格式化成字符串发送给客户端*/
        recv_to_Send(recv_buffer,sizeof(recv_buffer),send_buffer,sizeof(send_buffer));
        
        pthread_mutex_unlock(&g_db_mutex);

        /*==========<发送信息>==========*/
        send_bytes = send(tmpConnect->fd, send_buffer, strlen(send_buffer), 0);//因为不报含\0所以需要接收方手动加上一个\0
        if (send_bytes < 0)
        {
            perror("send");
            close(tmpConnect->fd);
            free(tmpConnect);
            break;
        }
    }
    return NULL;
}